<template>
    <div style="width: 100%;position: relative;height: 100%;">

        <div id="search">
            <el-form :model="listQuery" :inline="true" ref="formQuery" label-width="70px">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="文档名称" prop="docName">
                            <el-input size="small" style="width: 80%;" v-model="listQuery.docName"
                                      placeholder="请输入文档名称" clearable
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="docName">
                            <el-input size="small" style="width: 80%;" v-model="listQuery.projName"
                                      placeholder="请输入项目名称" clearable
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item>
                            <el-button type="success" size="small" icon="el-icon-document-add"
                                       @click="addDocument"></el-button>
                            <el-button size="small" type="primary" icon="el-icon-search" @click="search"></el-button>
                            <el-button size="small" @click="resetQuery('formQuery')">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <div id="table">
            <el-table border :data="list" style="width: 100%" v-loading="loading">
                <el-table-column type="index" width="65" label="#序号" align="center"/>
                <el-table-column prop="docName" label="文档名称" align="center"/>
                <el-table-column prop="projName" label="项目名称" align="center"/>
                <el-table-column prop="createTime" label="创建时间" align="center">
                    <template slot-scope="scope">
                        <i class="el-icon-time"></i>
                        <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" content="文件" placement="top-start">
                            <el-button size="small" type="text" icon="el-icon-document"
                                       @click="handleFile(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
                            <el-button size="small" type="text" icon="el-icon-edit"
                                       @click="handleEdit(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                            <el-button size="small" type="text" icon="el-icon-folder-delete"
                                       @click="handleDelete(scope.row)"
                            ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>

            </el-table>
            <!--分页-->
            <div class="block" style="margin-top: 10px;position: absolute;right: 0;">
                <el-pagination :page-sizes="[10]" :page-size="listQuery.pageSize" @current-change="handleCurrentChange"
                               layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </div>
        </div>

        <!--对话框-->
        <el-dialog title="文件下载" :visible.sync="dialogVisible" width="40%">
            <el-table :data="fileList" border>
                <!--<el-table-column type="selection" width="55"/>-->
                <el-table-column type="index" label="#序号" width="100" align="center"/>
                <el-table-column property="fileName" label="文件名" align="center"/>
                <el-table-column label="操作" align="center" width="120">
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" content="下载" placement="top-start">
                            <el-button size="small" type="text" icon="el-icon-download"
                                       @click="downloadFile(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                            <el-button size="small" type="text" icon="el-icon-document-delete"
                                       @click="deleteFile(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="dialogVisible = false" type="primary">取消</el-button>
            </div>
        </el-dialog>


        <!--新增文档对话框-->
        <el-dialog title="文档新增" :visible.sync="documentDialog" width="38%">
            <el-form ref="docForm" :rules="docRules" :model="docForm" label-position="left" label-width="80px"
                     style="width: 400px; margin-left:50px;">

                <el-form-item label="文档名称" prop="documentName">
                    <el-input size="small" v-model="docForm.documentName" placeholder="请输入项目名称"
                              style="width: 70%;"/>
                </el-form-item>
                <el-form-item label="项目" prop="projId">
                    <el-select style="width: 70%" size="small" v-model="docForm.projId"
                               filterable remote reserve-keyword clearable
                               placeholder="请输入项目名称" :remote-method="remoteProject"
                               :loading="projectLoading">
                        <el-option v-for="item in projOptions" :key="item.projId" :label="item.projName"
                                   :value="item.projId"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="文件" prop="document">
                    <el-upload class="upload-demo" multiple name="files" action="www.baidu.com" ref="upload"
                               :on-preview="handlePreview"
                               :on-change="changeDocument" :on-error="uploadError" :on-success="uploadSuccess"
                               :auto-upload="false">
                        <el-button slot="trigger" size="small" type="primary" icon="el-icon-document-add"></el-button>

                        <div slot="tip" class="el-upload__tip">只能上传.excel .doc文件，且不超过5M</div>
                    </el-upload>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size='medium' @click="documentDialog = false">取消</el-button>
                <el-button icon="el-icon-upload" size='medium'
                           type="primary" @click="submitUpload('docForm')">上传
                </el-button>
            </div>
        </el-dialog>


        <!--编辑文档对话框-->
        <el-dialog title="文档编辑" :visible.sync="editDialog" width="38%">
            <el-form ref="editForm" :rules="editDocRules" :model="editForm" label-position="left" label-width="80px"
                     style="width: 400px; margin-left:50px;">

                <el-form-item label="文档名称" prop="docName">
                    <el-input size="small" v-model="editForm.docName" placeholder="请输入项目名称"
                              style="width: 70%;"/>
                </el-form-item>
                <el-form-item label="项目" prop="projId">
                    <el-select style="width: 70%" size="small" v-model="editForm.projId"
                               filterable remote reserve-keyword clearable
                               placeholder="请输入项目名称" :remote-method="remoteProject"
                               :loading="projectLoading">
                        <el-option v-for="item in projOptions" :key="item.projId" :label="item.projName"
                                   :value="item.projId"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size='medium' @click="documentDialog = false">取消</el-button>
                <el-button icon="el-icon-upload" size='medium'
                           type="primary" @click="editDocument('editForm')">编辑
                </el-button>
            </div>
        </el-dialog>


    </div>
</template>

<script>
    export default {
        name: "document",
        data() {
            return {
                docId: null,
                loading: false,
                listQuery: {
                    pageSize: 10,
                    pageNum: 1
                },
                editForm: {
                    id: null,
                },
                total: undefined,
                list: [],
                fileList: [],
                dialogVisible: false,
                documentDialog: false,
                editDialog: false,
                projOptions: [],
                projectLoading: false,
                projId: "",
                docRules: {
                    projId: [{required: true, message: '请输入项目名称', trigger: 'change'}],
                    documentName: [{required: true, message: '请输入文档名称', trigger: 'blur'}],
                },
                editDocRules: {
                    projId: [{required: true, message: '请输入项目名称', trigger: 'change'}],
                    docName: [{required: true, message: '请输入文档名称', trigger: 'change'}],
                },
                docForm: {},
            }
        },
        methods: {
            //清空搜索条件
            resetQuery(formName) {
                this.$refs[formName].resetFields();
            },
            //编辑发送
            editDocument(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$post("/document/edit", this.editForm).then(res => {
                            if (res.code == 200) {
                                this.$message.success("编辑成功");
                                this.editDialog = false;
                                this.getList();
                            } else {
                                this.$message.error(res.msg);
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },

            //列表
            getList() {
                this.loading = true;
                this.$post("/document/list", this.listQuery).then(res => {
                    if (res.code == 200) {
                        this.list = res.data.records;
                        this.total = res.data.total;
                        this.loading = false;
                    }
                })
            },
            //搜索
            search() {
                this.listQuery.pageNum = 1;
                this.getList();
            },
            //分页改变
            handleCurrentChange(val) {
                this.listQuery.pageNum = val;
                this.getList();
            },
            //编辑
            handleEdit(row) {
                this.$get("/project/selectList").then(result => {
                    if (result.code == 200) {
                        this.projectLoading = false;
                        this.projOptions = result.data;
                    }
                });
                this.$get("/document/getDetail", {docId: row.id}).then(res => {
                    //console.log("res", res);
                    if (res.code == 200) {
                        this.editForm = res.data;
                        this.editDialog = true;
                    }
                });
            },
            //删除
            handleDelete(row) {
                this.$confirm('是否删除该文档, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$get("/document/delete", {docId: row.id}).then(res => {
                        if (res.code == 200) {
                            this.$message.success("删除成功");
                            this.getList();
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //打开文件下载列表
            handleFile(row) {
                this.docId = null;
                this.getFileList(row.id);
                this.docId = row.id;
            },
            //获取文件列表
            getFileList(docId) {
                this.$get("/document/getFile", {docId: docId}).then(res => {
                    if (res.code == 200) {
                        this.fileList = res.data;
                        this.dialogVisible = true;
                    }
                });
            },

            //下载文件
            downloadFile(row) {
                this.$get("/document/download", {filePath: row.fileUrl}, {"responseType": "blob"}).then(res => {
                  let blob = new Blob([res],{ type: 'application/vnd.ms-excel;charset=utf-8'});  //
                  //下载文件名称
                  let fileName = row.fileName;
                  if (window.navigator.msSaveOrOpenBlob) {
                    navigator.msSaveBlob(blob, fileName);
                  } else {
                    var link = document.createElement("a");
                    link.href = window.URL.createObjectURL(blob);
                    link.download = fileName;
                    link.click();
                    //释放内存
                    window.URL.revokeObjectURL(link.href);
                  }
                })
            },
            //增加文档
            addDocument() {
                this.docForm = {};
                this.fileList = [];
                this.documentDialog = true;
            },
            //上传成功的回调函数
            uploadSuccess(response, file, fileList) {
                console.log(response, fileList, file);
            },
            //上传失败的回调函数
            uploadError(err, file, fileList) {
                console.log(err, file, fileList);
            },
            handlePreview(file) {
                console.log(file);
            },
            //远程搜索项目
            remoteProject(query) {
                if (query !== '') {
                    this.projectLoading = true;
                    this.$get("/project/selectList").then(res => {
                        if (res.code == 200) {
                            this.projectLoading = false;
                            this.projectStates = res.data;
                            this.projOptions = this.projectStates.filter(item => {
                                return item.projName.indexOf(query) > -1;
                            });
                        }
                    })

                } else {
                    this.projOptions = [];
                }
            },
            //上传文件
            submitUpload(formName) {
                //console.log(this.fileList);
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (this.fileList.length <= 0) {
                            this.$message.warning("未选择上传文件");
                            return;
                        }
                        let formData = new FormData();
                        for (let i = 0; i < this.fileList.length; i++) {
                            formData.append("files", this.fileList[i]);
                        }

                        formData.append("projId", this.docForm.projId);
                        formData.append("documentName", this.docForm.documentName);
                        this.$post("/document/upload", formData).then(res => {
                            console.log(res);
                            if (res.code == 200) {
                                this.$notify.success("上传成功");
                                this.documentDialog = false;
                                //清楚上传文档列表
                                this.$refs.upload.clearFiles();
                                this.getList();
                            } else {
                                this.$notify.error(res.msg);
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            //文件改变
            changeDocument(file) {
                console.log(file);
                this.fileList.push(file.raw);
            },
            //文件删除
            deleteFile(row) {
                this.$confirm('是否删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$get("/file/delete", {fileId: row.id}).then(res => {
                        if (res.code == 200) {
                            this.$message.success("删除成功");
                            this.getFileList(this.docId);
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        },
        created() {
            this.getList();
        }
    }
</script>

<style scoped>
    #search {
        padding: 20px;
    }
</style>
